package com.travelms.service.commonuserpage.publicchat;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class Serve {
    static ArrayList<Socket> arrayList = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        //创建连接
        ServerSocket serverSocket = new ServerSocket(15000);
        System.out.println("服务端启动成功");
        //用线程处理读取数据
        while (true) {
            Socket socket = serverSocket.accept();
            System.out.println("有一个用户加入了连接");
            arrayList.add(socket);
            System.out.println("聊天室人数为:"  + arrayList.size());
            new Thread(new MyRunnable(socket,arrayList)).start();
        }


    }
}

 class  MyRunnable implements Runnable{
    Socket socket;
    ArrayList<Socket> arrayList;
    public MyRunnable(Socket socket,ArrayList<Socket> arrayList) {//创建线程时把来连接对象放入线程
        this.socket = socket;
        this.arrayList = arrayList;
    }

    @Override
    public void run() {


        //创建流处理数据
        try {

            while (true) {

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                String[] split = bufferedReader.readLine().split("-");

                if("exit".equals(split[1])){
                    break;
                }
                System.out.println(split[0] + ":" + split[1]);
                for (Socket socket1 : Serve.arrayList) {
                    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket1.getOutputStream()));
                    bufferedWriter.write(split[0] + ":" + split[1]);
                    bufferedWriter.newLine();
                    bufferedWriter.flush();

                }

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                socket.close();
                arrayList.remove(socket);
                System.out.println("聊天室人数为:"  + arrayList.size());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
